﻿using System.Collections;
using UnityEngine;

namespace cframework_coroutineutil
{
    public abstract class WaitBase : CustomYieldInstruction
    {
        public struct Result
        {
            public bool finished;
            public object result;
            public Coroutine coroutine;
            
        }

        public Result[] results;
        protected MonoBehaviour monobehaviour;

        protected WaitBase(params IEnumerator[] coroutines): this(CoroutineHelper.instance, coroutines)
        {
           
        }

        protected void StopAllCoroutine()
        {
            if (results == null) return;

            System.Array.ForEach(results, (result) =>
            {
                if (result.coroutine == null) return;

                monobehaviour.StopCoroutine(result.coroutine);
                result.coroutine = null;
            });
        }

        protected WaitBase(MonoBehaviour monoBehaviour, params IEnumerator[] coroutines)
        {
            this.monobehaviour = monoBehaviour;
            results = new Result[coroutines.Length];

            for (int i = 0; i < coroutines.Length; i++)
            {
                results[i].coroutine = monoBehaviour.StartCoroutine(Wrapper(coroutines[i], i));
            }
        }

        protected virtual IEnumerator Wrapper(IEnumerator e, int index)
        {
            //while (true)
            //{
            //    if(e != null && e.MoveNext())
            //    {
            //        _wait[index] = true; 
            //        yield return e.Current;
            //    }
            //    else
            //    {
            //        _wait[index] = false;
            //        break;
            //    }
            //}

            yield return e;

            results[index].result = e.Current;
            results[index].finished = true;
        }
    }
}